package com.jzbooks.result;

import com.jzbooks.enums.ResultCodeEnum;
import com.jzbooks.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;

import java.io.Serializable;
import java.util.Date;

/**
 * @author mingPeng
 * @date 2021/4/19 18:55
 * @Description : 自定义异常返回体
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErrorResult implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * HTTP响应状态码 {@link org.springframework.http.HttpStatus}
     */
    private Integer status;

    /**
     * 异常堆栈的精简信息
     *
     */
    private String message;

    /**
     *  错误状态码
     */
    private Integer code;

    /**
     * 异常的名字
     */
    private String exception;

    public static ErrorResult failure(ResultCodeEnum resultCodeEnum,Throwable e, HttpStatus httpStatus) {
        ErrorResult errorResult = new ErrorResult();
        errorResult.setCode(resultCodeEnum.getCode());
        errorResult.setMessage(resultCodeEnum.getMsg());
        errorResult.setStatus(httpStatus.value());
        errorResult.setException(e.getClass().getName());
        return errorResult;
    }

    public static ErrorResult failure(ErrorResult errorResult) {
        ErrorResult result = new ErrorResult();
        result.setCode(errorResult.getCode());
        result.setMessage(errorResult.getMessage());
        result.setStatus(errorResult.getStatus());
        return result;
    }

    public static ErrorResult failure(BusinessException e) {
        ErrorResult errorResult = ErrorResult
                .failure(e.getResultCodeEnum() == null ? ResultCodeEnum.SYSTEM_INNER_ERROR : e.getResultCodeEnum(),
                        e, HttpStatus.OK);
        errorResult.setMessage(e.getMessage());

        return errorResult;
    }
    
}
